package com.winning.sjzc.login.controller;

import static com.winning.sjzc.common.controller.BaseController.baseError;
import static com.winning.sjzc.common.controller.BaseController.successObjectResult;

import com.winning.sjzc.common.entity.po.SysYyzcEntity;
import com.winning.sjzc.common.service.SysYyzcService;
import com.winning.sjzc.common.utils.Des3Ces;
import com.winning.sjzc.common.utils.Util;
import com.winning.sjzc.login.entity.SysCzryEntity;
import com.winning.sjzc.login.entity.SysGncdEntity;
import com.winning.sjzc.login.service.LoginService;
import com.winning.sjzc.login.service.SysCzryJsService;
import com.winning.sjzc.login.service.SysCzryService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * description:系统登录类
 *
 * @author yanxf@winning.com.cn
 * @date 2019/08/07 11:24
 */
@Slf4j
@Controller
public class LoginController {

  @Autowired
  private SysYyzcService sysYyzcService;

  @Autowired
  private SysCzryService sysCzryService;

  @Autowired
  private LoginService loginService;

  @Autowired
  private SysCzryJsService sysCzryJsService;

  /**
   * 设置系统默认登录页
   * @param model
   * @return 登陆页面地址
   */
  @RequestMapping("/")
  public String defaultView(Model model){
    addModel(model);
    return "login";
  }

  private void addModel(Model model) {
    //查询系统信息（登录背景、登录图片、logo、展示名称）
    SysYyzcEntity sysYyzcEntity = sysYyzcService.getSysYyzc();
    model.addAttribute("yyms",sysYyzcEntity.getYyms());
    model.addAttribute("zsmc",sysYyzcEntity.getZsmc());
    model.addAttribute("dlbj",sysYyzcEntity.getDlbjmc());
    model.addAttribute("dltp",sysYyzcEntity.getDltpmc());
    model.addAttribute("yylogo",sysYyzcEntity.getYylogomc());
  }

  /**
   * 用户登录验证
   * @param username
   * @param password
   * @return
   */
  @PostMapping("/userLogin")
  @ResponseBody
  public Map<String, Object> userLogin(HttpServletRequest request, String username, String password){

    //用户信息
    SysCzryEntity user = sysCzryService.queryByUserName(username);

    //账号不存在、密码错误
    if (user == null || !user.getDlmm().equals(password)) {
      return baseError("账号或密码不正确!",500);
    }

    //账号锁定
    if ("N".equals(user.getQyzt())) {
      return baseError("账号已被锁定,请联系管理员!",500);
    }
    Map<String, Object> map = getLoginMap(user);
    request.getSession().setAttribute("loginUser", username);
    return successObjectResult("用户登录成功", map);
  }

  private Map<String, Object> getLoginMap(SysCzryEntity user) {
    //生成token，并保存到数据库
    String token = loginService.createToken(user);

    Map<String, Object> map = new HashMap<String, Object>(4);
    map.put("token", token);
    map.put("userName", user.getRyxm());
    map.put("zclsh", user.getZclsh());
    map.put("jgbm", user.getJgbm());
    return map;
  }

  @RequestMapping(value = "/logout", method = RequestMethod.GET)
  public String logout(HttpSession session, Model model) {
    session.invalidate();
    addModel(model);
    return "login";
  }

  @RequestMapping("/index")
  public String index(Model model, String username, String password, String sec, HttpServletRequest request){
    log.info("result:" + sec);
    if (StringUtils.isNotBlank(sec)) {
      try {
        //URL进行了Ecoder处理，解密时，需要做Des3.Decoder处理后，才可以解密
        String result = Des3Ces.decode(sec);
        username = result.split("dldm=")[1].split("&")[0];
        password = result.split("dlmm=")[1].split("&")[0];
        log.info("result:" + result);
        //用户信息
        SysCzryEntity user = sysCzryService.queryByUserName(username);

        //账号不存在、密码错误
        if (user == null || !user.getDlmm().equals(password)) {
          return "login";
        }

        //账号锁定
        if ("N".equals(user.getQyzt())) {
          return "login";
        }
        request.getSession().setAttribute("loginUser", username);
        //生成token，并保存到数据库
        String token = loginService.createToken(user);
        model.addAttribute("token",token);
        model.addAttribute("userName",user.getRyxm());
        model.addAttribute("zclsh",user.getZclsh());
        model.addAttribute("jgbm",user.getJgbm());
      } catch (Exception e) {
        log.error("解密异常：", e);
      }
    }else {
       username = (String) request.getSession().getAttribute("loginUser");
       if (StringUtils.isEmpty(username)) {
         return "login";
       }
    }

    return "index";
  }

  @RequestMapping("/home")
  public String home(){
    return "home";
  }

  /**
   * 查询一级导航菜单
   * @param zclsh 操作人员注册流水号
   * @return
   */
  @RequestMapping(value = "/queryNavigationMenu", method = RequestMethod.GET)
  @ResponseBody
  public Map<String, Object> queryNavigationMenu(String zclsh) {
    List<SysGncdEntity> list = loginService.queryNavigationMenu(sysCzryJsService.getJsbmList(zclsh));
    Map<String,Object> map = new HashMap<String,Object>();
    map.put("menulist", list);
    return successObjectResult("查询成功",map);
  }

  /**
   * 查询2、3级菜单
   * @param mcode
   * @param zclsh
   * @return
   */
  @RequestMapping(value = "/querySubMenu", method = RequestMethod.GET)
  @ResponseBody
  public Map<String, Object> querySubMenu(String mcode,String zclsh) {
    if (!Util.validateParams(mcode)) {
      return baseError("菜单不能为空",201);
    }
    List<String> jgbmList = sysCzryJsService.getJsbmList(zclsh);
    //查询菜单
    Map<String, Object> menuMap = loginService.querySubMenu(mcode, jgbmList);
    return successObjectResult("查询成功",menuMap);
  }
}
